console.log("用户管理系统已启动！");
document.addEventListener('DOMContentLoaded', function() {
    const addUserBtn = document.getElementById('btnAddUser');
    const userTableBody = document.getElementById('userTableBody');
    const refreshBtn = document.getElementById('btnRefresh');

    let userIdCounter = 1;

    function addUserToTable(user) {
        const newRow = document.createElement('tr');
        newRow.innerHTML = `
            <td class="text-center">${user.id}</td>
            <td><strong>${user.name}</strong></td>
            <td>${user.email}</td>
            <td>${user.phone}</td>
            <td>${user.registerTime}</td>
            <td class="text-center">
                <button id="edit-btn-${user.id}"
                        class="btn btn-sm btn-outline-primary me-1 edit-btn"
                        title="编辑" data-user-id="${user.id}"
                        onclick="handleEditUser(${user.id},'${user.name}')">
                    <i class="fas fa-edit"></i>
                </button>
                <button id="delete-btn-${user.id}"
                        class="btn btn-sm btn-outline-danger delete-btn"
                        title="删除" data-user-id="${user.id}"
                        onclick="handleDeleteUser(${user.id},'${user.name}')">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        userTableBody.appendChild(newRow);
    }

    function loadDefaultData() {
        const defaultUsers = [
            {id:1,name:'张三',email:'zhangsan@example.com',phone:'13800138000',registerTime:'2025-09-01 10:30:00'},
            {id:2,name:'李四',email:'lisi@example.com',phone:'13900139000',registerTime:'2025-09-02 14:15:00'},
        ];

        defaultUsers.forEach(user => {
            addUserToTable(user);
        });

        userIdCounter = defaultUsers.length + 1; // 修正变量名
    }

    loadDefaultData();

    addUserBtn.addEventListener('click', function() {
        const newUser = {
            id: getNextUserId(),
            name: '新用户' + userIdCounter,
            email: 'newuser' + userIdCounter + '@example.com',
            phone: '1380013800' + (userIdCounter % 10),
            registerTime: new Date().toLocaleString() // 修正时间对象
        };
        addUserToTable(newUser);
        updateUsersCount();
        Toastify({
            text: "成功添加用户",
            duration: 3000,
            close: true,
            gravity: "top",
            position: "right",
            backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)", // 修正渐变拼写
            style: {
                borderRadius: "10px"
            }
        }).showToast();
        userIdCounter++;
    });

    function handleDeleteUser(userId, userName) {
        console.log(`删除用户 ID: ${userId},姓名： ${userName}`);
        // 修正按钮ID选择器（添加连字符）
        const rowToDelete = document.getElementById(`edit-btn-${userId}`).closest('tr');
        rowToDelete.remove();
        updateUsersCount();
        Toastify({
            text: `用户 "${userName}" 删除成功`,
            duration: 3000,
            close: true,
            gravity: "top",
            position: "right",
            backgroundColor: "linear-gradient(to right, #ff5f6d, #ffc371)", // 修正渐变拼写
            style: {
                borderRadius: "10px"
            }
        }).showToast();
    }
    window.handleDeleteUser = handleDeleteUser;

    function handleEditUser(userId, userName) {
        console.log(`编辑用户 ID: ${userId}, 姓名: ${userName}`);
        Toastify({
            text: `编辑用户: ${userName} (ID: ${userId}) (功能待实现)`,
            duration: 3000,
            close: true,
            gravity: "top",
            position: "right",
            backgroundColor: "linear-gradient(to right, #667eea, #764ba2)", // 修正渐变拼写
            style: {
                borderRadius: "10px"
            }
        }).showToast();
    }
    window.handleEditUser = handleEditUser;

    refreshBtn.addEventListener('click', function() {
        while (userTableBody.firstChild) {
            userTableBody.removeChild(userTableBody.firstChild);
        }
        loadDefaultData();
        userIdCounter = 1;
        updateUsersCount();
        Toastify({
            text: "用户数据已刷新",
            duration: 3000,
            close: true,
            gravity: "top",
            position: "right",
            backgroundColor: "linear-gradient(to right, #1e3c72, #2a5298)", // 修正渐变拼写
            style: {
                borderRadius: "10px"
            }
        }).showToast();
    });

    function updateUsersCount() {
        // 修正行数计算方式
        document.getElementById('userCount').textContent = userTableBody.rows.length;
    }

    function getNextUserId() {
        const existingRows = userTableBody.rows;
        let maxId = 0;
        for (let i = 0; i < existingRows.length; i++) {
            const currentId = parseInt(existingRows[i].cells[0].textContent);
            if (currentId > maxId) {
                maxId = currentId;
            }
        }
        return maxId + 1;
    }
});
